package cn.action;

import cn.entity.User;
import cn.service.UserService;
import cn.service.impl.UserServiceImpl;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.struts2.ServletActionContext;

import javax.servlet.http.HttpServletRequest;

public class LoginAction extends ActionSupport {



    private String name;
    private String password;
    private UserService userService = new UserServiceImpl();

    @Override
    public String execute() throws Exception {
        User user = userService.login(name,password);
        HttpServletRequest request = ServletActionContext.getRequest();
        if (user==null){
            addFieldError("user","用户不存在");
            return INPUT;
        }else if (!user.getPassword().equals(password)){
            addFieldError("pwd","密码错误");
            return INPUT;
        }else {
            request.getSession().setAttribute("user",user);
            return SUCCESS;
        }

    }

    @Override
    public void validate() {
        if (this.getName()==null||this.getName().length()==0||
                this.getPassword()==null||this.getPassword().length()==0){
            addFieldError("error","登录失败，请检查用户名或密码是否正确");
        }
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
